package com.zzzzzz.account.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzzzzz.account.model.LoginForm;
import com.zzzzzz.account.service.UserService;
import com.zzzzzz.core.exception.NoSuchUserException;
import com.zzzzzz.core.exception.UserActiveException;

/**
 * Web MVC controller that handles security-related web requests, such as login and logout.
 */

@Controller
public class SecurityController {

	@Resource
	private UserService userService;

    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String viewLoginPage(Model model, @ModelAttribute LoginForm loginForm) {
		model.addAttribute("cur", "login");
        return "account/login";
    }

    @RequestMapping(value="/login",method= RequestMethod.POST)
    public String processLogin(Model model, @ModelAttribute LoginForm loginForm, BindingResult result, HttpServletRequest request) throws Exception {
        if(result.hasErrors()) {
    		result.reject("message.error.process.request");
            return viewLoginPage(model, loginForm);
        }
        try {
    		String loginType = request.getParameter("login-type");
    		if("dropdown".equalsIgnoreCase(loginType)) {
        		String loginDropdownEmail = request.getParameter("login-dropdown-email");
        		String loginDropdownPasswordl = request.getParameter("login-dropdown-password");
        		String loginDropdownRememberMe = request.getParameter("login-dropdown-rememberme");
            	userService.login(loginDropdownEmail, loginDropdownPasswordl, Boolean.valueOf(loginDropdownRememberMe));
    		}else {
            	userService.login(loginForm.getEmail(), loginForm.getPassword(), loginForm.isRememberMe());
    		}
    		
    		return "redirect:/";
			
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
	            result.reject("message.error.login.generic");
			}else if(e instanceof AuthenticationException) {
	            result.reject("message.error.login.generic");
			}else if(e instanceof UserActiveException) {
        		result.reject( "message.error.login.account.unactivated");
			}else {
				logger.error(e.getMessage(), e);
				throw e; // handle by Spring
			}
		}

        return viewLoginPage(model, loginForm);
        
    }

    @RequestMapping("/logout")
    public String processLogout() {
		Subject currentUser = SecurityUtils.getSubject();
//		Session session = currentUser.getSession();
//		session.removeAttribute("currentUser");
		currentUser.logout(); //removes all identifying information and invalidates their session too.
        return "redirect:/";
    }
    
    private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);
}
